package com.hnepri.fang.ftx2.fetch.index;

import com.hnepri.fang.ftx2.fetch.APageBridge;
import com.hnepri.fang.ftx2.model.Residential;
import com.hnepri.util.FileUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ResidentialIndexThread extends Thread{
    APageBridge pageBridge;
    private List<Residential> residentials;
    private String pPath;
    private int startIndex;
    private int endIndex;


    public ResidentialIndexThread(APageBridge pageBridge, List<Residential> residentials, String pPath, int startIndex, int endIndex) {
        this.setName("thread-" + startIndex + "-" + endIndex);
        this.pageBridge = pageBridge;
        this.residentials = residentials;
        this.pPath = pPath;
        this.startIndex = startIndex;
        this.endIndex = endIndex;
    }

    @Override
    public void run() {
        List<String> infos = new ArrayList<>();
        String path = this.pPath + "/" + this.getName() + ".txt";
        for (int i = startIndex; i <= endIndex; i++) {
            try {
                String url = residentials.get(i).getDomain();
                String id = residentials.get(i).getId();
                if (url == null || url.trim().equals("") || url.indexOf("http") != 0) {
                    continue;
                }
                System.out.println("开始获取URL：" + url);
                String info = pageBridge.getPageInfo(url);
                if (info != null) {
                    infos.add("fid:" + id + "|" + info);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (infos.size() > 0) {
            FileUtil.writeLines(infos,path, "utf-8");
        }
    }
}
